//
//  MCViewController.m
//  MClient
//
//  Created by  史正烨 on 10-8-23.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "MCViewController.h"
#import "MCErrorManagement.h"
#import "MultiTitleView.h"
#import "LoginController.h"
#import "UIDeviceHelper.h"

@implementation UIViewController(MClient)
- (UIView *)clientView {
	return nil;
}
- (NSData*)serialized {
	return nil;
}
//反序列化页面数据
- (void)deserialized {
}

- (void)viewDidLoad {
	[self deserialized];
}
@end

@interface MCViewController(Private)
- (void)resetSubViewFrame;
@end

#pragma mark -------- MCViewController ----------
@implementation MCViewController

//@synthesize nScreenWidth, nScreenHeight;
@synthesize addHelpButton = bAddHelpBtn;
@synthesize helpUrl;
@synthesize identiferId;

- (MClientAppDelegate*)appDelegate {
	return (MClientAppDelegate*)[[UIApplication sharedApplication] delegate];
}

- (MCUserDefaults*)userDefaults {
	return (MCUserDefaults*)[MCUserDefaults instance]; 
}

- (MCImageObject*)imgObject {
	return (MCImageObject*)[MCImageObject instance]; 
}

- (MCConfigCache*)configCache {
	return (MCConfigCache*)[MCConfigCache instance]; 
}

- (UIView *)clientView {
	return clientView;
}

- (id)init
{
	if (self = [super init]) {
        // Custom initialization
		bAddHelpBtn = FALSE;
		helpButton  = nil;
		identiferId = kInvalidIdentiferID;
		rightNaviButtonAdded = NO;
    }
    return self;
}

- (void)registerForKeyboardNotifications
{
	[[NSNotificationCenter defaultCenter] addObserver:self
											 selector:@selector(keyboardWillShown:)
												 name:UIKeyboardWillShowNotification object:nil];
	
    [[NSNotificationCenter defaultCenter] addObserver:self
											 selector:@selector(keyboardDidShown:)
												 name:UIKeyboardDidShowNotification object:nil];
	
    [[NSNotificationCenter defaultCenter] addObserver:self
											 selector:@selector(keyboardDidHidden:)
												 name:UIKeyboardDidHideNotification object:nil];
}

- (void)unregisterForKeyboardNotifications
{
	[[NSNotificationCenter defaultCenter] removeObserver:self 
													name:UIKeyboardWillShowNotification 
												  object:nil];
	
	[[NSNotificationCenter defaultCenter] removeObserver:self 
													name:UIKeyboardDidShowNotification 
												  object:nil];
	
	[[NSNotificationCenter defaultCenter] removeObserver:self 
													name:UIKeyboardDidHideNotification 
												  object:nil];
}

- (BOOL)isVertical {
	return CGRectGetWidth(self.view.frame) < CGRectGetHeight(self.view.frame);
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	
	// navigationbar背景颜色设置
	if (self.userDefaults.hideNavigationBar && self.identiferId == kInvalidIdentiferID && 
		self.userDefaults.needLogoHeader && [self isVertical]) {
		self.navigationController.navigationBarHidden = YES;
	} else {
		self.navigationController.navigationBarHidden = NO;
	}
	self.navigationController.navigationBar.tintColor = self.userDefaults.skin_navigationBarColor;
	
	MCUserDefaults* defaults = [MCUserDefaults instance];
	if (self.identiferId == kInvalidIdentiferID && defaults.needLogoHeader && [self isVertical]) {
		int nlogoHeight = [[defaults.logoHeader objectForKey:@"height"] intValue];
		clientView = [[UIView alloc] initWithFrame:CGRectMake(0, nlogoHeight, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds)-nlogoHeight)];
		
		UIImageView* logoView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), nlogoHeight)];
		logoView.image = defaults.skin_logoTitle;
		//logoView.autoresizingMask = nMCViewAutoresizingMask;
		logoView.tag = - 234;
		[self.view addSubview:logoView];
		[logoView release];
		[self.view addSubview:clientView];
		[self.view sendSubviewToBack:clientView];
	} else {
		clientView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds))];
		self.view = clientView;
	}
	/*
	clientView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin|
								  UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleBottomMargin|
								  UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
	clientView.backgroundColor = [UIColor clearColor];*/
	[self resetBackground];
	//[self.view addSubview:clientView];
	//[self.view sendSubviewToBack:clientView];
	
	if (self.tabBarController) {
		tabBarTitle = self.tabBarItem.title;
	} else {
		tabBarTitle = @"";
	}
}

- (void)resetBackground {
}

- (void)viewWillAppear:(BOOL)animated
{
	if (bAddHelpBtn && nil == helpButton && self.userDefaults.isShowHelp) {
		helpButton = [MCFunction createHelpButton:self selector:@selector(doHelp:) frame:CGRectMake(CGRectGetWidth(self.view.bounds)-50, CGRectGetHeight(self.view.bounds)-46,48, 48)];
		helpButton.autoresizingMask = nMCViewAutoresizingMask | UIViewAutoresizingFlexibleHeight;
		[helpButton retain];
		[self.view addSubview:helpButton];
	}
	
	[self resetSubViewFrame];
	[self backBarButton:@"返回"];
}

- (void)viewDidAppear:(BOOL)animated
{
	[self registerForKeyboardNotifications];
}


- (void)viewDidDisappear:(BOOL)animated
{
	[self unregisterForKeyboardNotifications];
}


- (void)dealloc {
	MCLog(@"-----------%@ dealloc------------", [self description]);
	
	[clientView release];
	[bgView release];
	[helpButton release];
	[[NSNotificationCenter defaultCenter] postNotificationName:@"viewControllerDealloc" object:self];
    [super dealloc];
}


#pragma mark -- navigationBarItems --
- (void)backBarButton:(NSString*)aTitle
{
//	UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] init];
//	barButtonItem.title = aTitle;
//	self.navigationItem.backBarButtonItem = barButtonItem;
//	[barButtonItem release];
//	barButtonItem = nil;
}

- (void)rightBarButton:(NSString*)aTitle withStyle:(UIBarButtonItemStyle)style selector:(SEL)sel
{
	if (!rightNaviButtonAdded) {
		UIBarButtonItem *button = [[UIBarButtonItem alloc]
								   initWithTitle:aTitle 
								   style:style 
								   target:self
								   action:sel];
		self.rightBarButtonItem = button;
		[button release]; button = nil;
	}
}

- (void)leftBarButton:(NSString*)aTitle withStyle:(UIBarButtonItemStyle)style selector:(SEL)sel
{
	//UIBarButtonItem *button = [[UIBarButtonItem alloc]
//							   initWithTitle:aTitle 
//							   style:style 
//							   target:self
//							   action:sel];
//	self.navigationItem.leftBarButtonItem = button;
//	[button release]; button = nil;
}

#pragma mark 弹出消息框
// 弹出消息框
- (void)messageBox:(NSString *)title message:(NSString *)message delegate:(id)delegate 
 cancelButtonTitle:(NSString *)cancelButtonTitle otherButtonTitles:(NSString *)otherButtonTitles
{
	//va_list args;
	//va_start(args, otherButtonTitles);
	UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title message:message delegate:delegate 
											  cancelButtonTitle:cancelButtonTitle 
							                  otherButtonTitles:otherButtonTitles, nil];
	//va_end(args);
	[alertView show];
	[alertView release];
}

- (void)getServerError: (NSString *)returnCode returnMessage:(NSString *)returnMessage
{
	[[MCErrorManagement instance] doError:returnCode returnMessage:returnMessage];
}

// 从服务器取数据成功消息
- (void)getServerSuccess: (NSString *)returnCode returnMessage:(NSString *)returnMessage
{
	[self messageBox:returnMessage message:nil delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定"];
}

- (void)doHelp:(id)sender {
	MCWebViewController *helpController = [[MCWebViewController alloc] init];
	helpController.title = @"帮助信息";
	[self.navigationController pushViewController:helpController animated:YES];
	if (helpUrl == nil) {
		helpUrl = @"/iphone/help/index.html";
	}
	NSString *url = [self.userDefaults.current_ServerUrl stringByAppendingString:helpUrl];
	[helpController loadHTMLfromURL:url];
	[helpController release];
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (UIView*)findFirstResponder {
	return [self findFirstResponderInView:self.view];
}


///////////////////////////////////////////////////////////////////////////////////////////////////
- (UIView*)findFirstResponderInView:(UIView*)topView {
	if ([topView isFirstResponder]) {
		return topView;
	}
	
	for (UIView* subView in topView.subviews) {
		if ([subView isFirstResponder]) {
			return subView;
		}
		
		UIView* firstResponderCheck = [self findFirstResponderInView:subView];
		if (nil != firstResponderCheck) {
			return firstResponderCheck;
		}
	}
	return nil;
}

- (float)width {
	return CGRectGetWidth(self.clientView.bounds);
}
- (float)height {
	return CGRectGetHeight(self.clientView.bounds);
}

// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation 
{
	return self.userDefaults.needScreenVHChange;
}

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
	[super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
	
	[self resetSubViewFrame];
}

- (void)resetSubViewFrame {
	
	if (self.userDefaults.hideNavigationBar && self.identiferId == kInvalidIdentiferID && 
		self.userDefaults.needLogoHeader && [self isVertical]) {
		self.navigationController.navigationBarHidden = YES;
	}// else {
//		self.navigationController.navigationBarHidden = NO;
//	}

	MCUserDefaults* defaults = [MCUserDefaults instance];
	if (self.identiferId == kInvalidIdentiferID && defaults.needLogoHeader && [self isVertical]) {
		int nlogoHeight = [[defaults.logoHeader objectForKey:@"height"] intValue];
		[self.view viewWithTag:-234].frame = CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), nlogoHeight);

		clientView.frame = CGRectMake(0, nlogoHeight, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds)-nlogoHeight);
		
		[self.view viewWithTag:-234].hidden = NO;
	}// else {
//		clientView.frame = CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds));
//		
//		
//		[self.view viewWithTag:-234].hidden = YES;
//	}
	[self setLoginButton];
}

- (void) setLoginButton {
	return;
}


- (void)setTitle:(NSString *)title {
//	super.title = [NSString stringWithFormat:@"%f",[UIDevice currentDevice].availableMemory];
//	return;
	
	NSString* _titleTrimed = [title stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
	NSArray* titles = [_titleTrimed componentsSeparatedByString:@"||"];
	if ([titles count] > 0) {
		super.title = [titles objectAtIndex:0];
	} else {
		super.title = tabBarTitle;
		return;
	}

	if ([titles count] > 1) {
		MultiTitleView* _titleView = [[[MultiTitleView alloc] create] autorelease];
		self.navigationItem.titleView = _titleView;
		[_titleView setMainTitle:self.title];
		[_titleView setSubTitle:[titles objectAtIndex:1]];
	}
}

- (UIBarButtonItem *) rightBarButtonItem {
	return self.navigationItem.rightBarButtonItem;
}

- (void) setRightBarButtonItem:(UIBarButtonItem *)item {
	self.navigationItem.rightBarButtonItem = item;
}

- (NSString *) rightBarButtonItemTitle {
	return self.navigationItem.rightBarButtonItem.title;
}

- (void) setRightBarButtonItemTitle:(NSString *)title {
	self.navigationItem.rightBarButtonItem.title = title;
}

@end

